package nr.co.mhgames.polyanim;

import java.util.EnumMap;

/**
 * A collection of {@link Animation Animations} implemented as an
 * {@link java.util.EnumMap}. You need to supply an enumeration of the different
 * animation states you want to store to the class constructor.
 * <p>
 * Why we use <b>EnumMap</b> instead of plain Strings? The answer is efficiency;
 * String hashing is much slower than enum hashing (since enum is a hash
 * already). You can use a simple HashMap&lt;String, Animation&gt; if you need
 * String-based storage.
 * <p>
 * For example, let's say you have an enum of player states:
 * 
 * <pre>
 * enum PlayerState {
 * 	RUNNING, WALKING, IDLE
 * };
 * </pre>
 * 
 * To instantiate a collection of the animations for the player state, you could
 * do:
 * 
 * <pre>
 * // Create the collection
 * AnimationCollection&lt;PlayerState&gt; stateAnims = new AnimationCollection&lt;PlayerState&gt;(
 * 		PlayerState.class);
 * 
 * // Store the animations
 * stateAnims.putAnimation(PlayerState.RUNNING, runningAnim);
 * stateAnims.putAnimation(PlayerState.WALKING, walkingAnim);
 * stateAnims.putAnimation(PlayerState.IDLE, idleAnim);
 * </pre>
 * 
 * @author Mika Halttunen
 * @param <T>
 *            Enumeration of the animations you want to store
 */
public class AnimationCollection<T extends Enum<T>> {
	/** Map of the animations */
	private final EnumMap<T, Animation> animations;

	/**
	 * Constructor. Supply the class of the enumeration you want to store.
	 * 
	 * @param enumClass
	 *            Class of the enumeration
	 */
	public AnimationCollection(Class<T> enumClass) {
		animations = new EnumMap<T, Animation>(enumClass);
	}


	/**
	 * Store an animation by the ID specified as an enumeration value to the
	 * collection.
	 * 
	 * @param id
	 *            The ID as an enumeration value
	 * @param animation
	 *            Animation to store
	 */
	public void putAnimation(T id, Animation animation) {
		animations.put(id, animation);
	}

	/**
	 * Get an animation with the given ID from the collection.
	 * 
	 * @param id
	 *            The ID as an enumeration value
	 * @return The corresponding animation, or <code>null</code> if not found.
	 */
	public Animation getAnimation(T id) {
		return animations.get(id);
	}

	/**
	 * Checks if the collection contains an animation for the given ID.
	 * 
	 * @param id
	 *            The ID as an enumeration value
	 * @return <code>true</code> if there is an animation with that ID
	 */
	public boolean hasAnimation(T id) {
		return animations.get(id) != null;
	}


	/**
	 * Returns the amount of stored animations in the collection.
	 * 
	 * @return Animation count
	 */
	public int size() {
		return animations.size();
	}
}
